#include <iostream>
#include "GuiHelper.h"
#include "QtGui/QtGui"
using namespace std;

GuiHelper::GuiHelper(void)
{
	useQT = false;
}


GuiHelper::~GuiHelper(void)
{
}

GuiHelper* GuiHelper::getInstance( void )
{
	if (me == NULL)
		me = new GuiHelper;
	return me;
}

void GuiHelper::setUseQT()
{
	useQT = true;
}

void GuiHelper::createWindow()
{
	if (!useQT)
		cv::namedWindow("EOF", CV_WINDOW_FREERATIO | CV_WINDOW_AUTOSIZE | CV_GUI_NORMAL);
}

void GuiHelper::draw( cv::Mat& img )
{
	if (!useQT)
		imshow("EOF", img);
	else {
		QWidgetList qwlist = qApp->allWidgets();
		QWidget* qw;
		for (int i=0; i<qwlist.size(); ++i) {
			qw = qwlist[i];
			cout << qw->objectName().toStdString() << endl;
			if (qw->objectName().compare("label") == 0)
				break;
		}
		QLabel *label = dynamic_cast<QLabel *>(qw);
		if (NULL != label)
		{
			cout << "this is a label" << endl;
			QImage* qimg = opencv2QT(img);
			QPixmap pix;
			pix.fromImage(*qimg);
			label->setPixmap(pix);
			system("pause");
		}
	}

}

QImage* GuiHelper::opencv2QT( cv::Mat& x )
{
	cout << x.size().width << " " << x.size().height << endl;
	cv::Mat y(x.size(), CV_8UC3);
	if (x.channels() == 1) {
		merge(&x,3,y);
	}
	else {
		y = x;
	}
	const uchar* data = y.data;
	imshow("test", y);
	int width = y.cols;
	int height = y.rows;
	int bytesPerLine = width*8*3;

	QImage* qimage = new QImage( data, width, height, bytesPerLine, QImage::Format_RGB32 );

	return qimage;
}

GuiHelper* GuiHelper::me = NULL;
